<template>
  <view>
    <u-popup :show="isShow"
      mode="center"
      @close="cancel"
      bgColor="transparent">
      <view class="coupon">
        <view class="coupon__center">
          <image src="http://medusa-small-file.oss-cn-hangzhou.aliyuncs.com/api/head1.png"
            style="width: 100%;height: 29%;margin-top: -20px;"></image>
          <view class="coupon__center--allList" :style="'height:50%;'">
            <view v-for="(coupon, index) in couponList" :key="index" style="margin-top:10rpx">
              <index-coupon :coupon="coupon" @getCoupon="getCoupon"></index-coupon>
            </view>
          </view>
          <view style="height: 10%;padding-top: 5px" v-if="couponList.length>0">
            <view class="getBtn" @click="getAll" v-if="canGet">一键领取</view>
          </view>
          <view style="height: 20%;padding-top: 5px" v-else>
            <view class="nogetBtn">暂无可领优惠券</view>
          </view>
        </view>
        <u-icon name="close-circle-fill" size="28" color="white" @click="cancel"></u-icon>
      </view>
    </u-popup>
    <auth :authType="authType" @authClick="authClick"></auth>
    <image src="http://medusa-small-file.oss-cn-hangzhou.aliyuncs.com/api/float.gif" :lazy-load="true" class="floatGif"
      :animation="animation" v-if="!isShow" @click="couponPop"></image>
  </view>
</template>

<script lang="ts">
  import {
    Component,
    Vue,
    Prop
  } from 'vue-property-decorator'
  import {
    getCouponIndex,
    getOneCoupon,
    getAllCoupon,
  } from "@/api/modules/coupon";
  import {
    loginGetInt
  } from "@/api/modules/integral";
  import IndexCoupon from "@/components/couponCom/index-coupon/indexCoupon.vue"
  import Auth from "@/components/auth/auth.vue";

  @Component({
    components: {
      IndexCoupon,
      Auth
    }
  })
  export default class HomeCoupon extends Vue {
    @Prop({
      type: Boolean,
      default: false
    })
    couponType: Boolean
    @Prop() animation: any

    couponList: Array < any > = []
    isShow: Boolean = false
    authType: Boolean = false
    canGet: Boolean = true

    timeout: number

    // 组件周期函数--监听组件挂载完毕
    mounted() {
      // if (this.$store.state.userStore.userInfo.token) {
      this.getCouponList();
      this.isShow = false
      this.$emit("stopRoll", false);
      const nowDay = Math.floor((+new Date())/(1000*60*60*24))
      const storageDay = uni.getStorageSync('couponDay')
      if(!storageDay || nowDay > storageDay){
        this.appLaunchInit();
      }
    }

    async appLaunchInit() {
      await this.getCouponList();
      let userInfo = this.$store.state.userStore.userInfo
      userInfo = {
        ...userInfo,
        couponType: false
      }
      this.$store.commit("userStore/setUserInfo", userInfo)
      const nowDay = Math.floor((+new Date())/(1000*60*60*24))
      if (this.couponList.length > 0) {
        this.isShow = true
        uni.setStorageSync('couponDay', nowDay)
        this.$emit("stopRoll", true);
      }
    }

    authClick(){
      this.setData({
          authType: false,
      });
    }

    /**
     * 获取首页优惠券
     */
    async getCouponList() {
      const shopMsg = this.$store.state.shopset.shopInfo;
      if (!shopMsg || shopMsg.status !== 2) return;

      const res = await getCouponIndex({})
      this.juageUserLogin();
      if (!res.length) {
        this.$emit("stopRoll", false);
        return;
      }
      res.forEach((item, index) => {
        item.hasUse = false;
        item.index = index;
        item.restNum =
          item.available > item.totalAvailable ?
          item.totalAvailable :
          item.available;
      });
      this.couponList = res
      this.canGet = true
    }

    /**
     * 判断用户登录能否在获得积分
     */
    async juageUserLogin() {
      const userInfo = this.$store.state.userStore.userInfo;
      if (!userInfo.whetherAuthorization) return;
      if (!this.$store.state.settingStore.integral.load) return;
      const res = await loginGetInt({});
      if (res) {
        uni.showToast({
          title: `登录成功,获得${res}积分`,
          icon: "none"
        });
      }
    }

    /**
     * 领取优惠券
     * @param options
     */
    getCoupon(options) {
      const userInfo = this.$store.state.userStore.userInfo;
      if (!userInfo.whetherAuthorization) {
        this.authType = true
        this.isShow = false
        this.$emit("stopRoll", false);
        return;
      }
      const currentItem = this.couponList[options.index];
      getOneCoupon(options.id, {})
        .then(() => {
          currentItem.restNum = currentItem.restNum - 1;
          if (currentItem.restNum === 0) {
            currentItem.hasUse = !currentItem.hasUse;
          }
          this.couponList[options.index] = currentItem
          uni.showToast({
            title: "领取成功",
            icon: "none",
            duration: 500
          });
        })
        .catch(() => {
          uni.showToast({
            title: "优惠券已被领光",
            icon: "none",
            duration: 1000
          });
          currentItem.hasUse = !currentItem.hasUse;
          this.couponList[options.detail.index] = currentItem
        });
    }

    /**
     * 一键获取所有
     */
    getAll() {
      const userInfo = this.$store.state.userStore.userInfo;
      if (!userInfo.whetherAuthorization) {
        this.authType = true
        this.isShow = false
        this.$emit("stopRoll", false);
        return;
      }
      if (this.timeout) {
        clearTimeout(this.timeout);
      }
      this.timeout = setTimeout(() => {
        const ids = [] as any;
        this.couponList.forEach((item: any) => {
          item.hasUse = true;
          ids.push(item.id);
        });
        getAllCoupon(ids, {}).then(() => {
          uni.showToast({
            title: "领取成功,可在我的优惠券查看",
            icon: "none"
          });
          this.canGet = false
        });
      }, 300);
    }

    cancel() {
      const type = this.couponList.every((item: any) => {
        return item.hasUse === true;
      });
      this.$emit("cancel", type ? 1 : 0);
      // this.store.settingStore.tabVisible = true;
      let userInfo = this.$store.state.userStore.userInfo
      userInfo = {
        ...userInfo,
        couponType: true
      }
      this.isShow = false;
      this.$store.commit("userStore/setUserInfo", userInfo)
      this.$emit("stopRoll", false);
    }

    /**
     * 显示弹窗
     */
    async couponPop() {
      await this.getCouponList();
      // this.store.settingStore.tabVisible = false;
        this.setData({
          isShow: true
        })
        this.$emit("stopRoll", true);
      

      // this.isShow = true;
      // userInfo = this.$store.state.userStore.userInfo
      const userInfo = {
        ...this.$store.state.userStore.userInfo,
        couponType: true
      }
      this.$store.commit("userStore/setUserInfo", userInfo)
    }

    /**
     * 隐藏优惠券
     */
    hideCoupon() {
      this.isShow = false
    }
  }
</script>

<style lang="scss" scoped>
  @include b(coupon) {
    position: relative;
    // top: 0;
    width: 600rpx;
    height: 1000rpx;
    // padding-top: 30px;
    // background-color: rgba(0, 0, 0, 00);
    // background-color: rgba(0,0,0,0);
    background: transparent;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
    z-index: 100;
    padding-top: 13.5px;

    @include e(center) {
      // width: 82%;
      width: 93%;
      height: 90%;
      background-color: #f97417;
      display: flex;
      justify-content: center;
      flex-wrap: wrap;

      @include m(icon) {
        position: absolute;
        bottom: -5px;
        font-size: 28px;
        color: #dbd5cf;
      }

      @include m(allList) {
        display: flex;
        justify-content: center;
        flex-wrap: wrap;
        // height: 340px;
        // height: 67%;
        overflow-y: scroll;
        overflow-x: hidden;
      }
    }
  }

  // .coupon__center--allList::-webkit-scrollbar {
  //     display: none;
  // }

  .getBtn {
    width: 100px;
    height: 30px;
    background-color: #ff9900;
    color: #fde2b6;
    @include flex(center, center);
  }

  .nogetBtn{
   width: 150px;
   height: 40px;
   color: #ffffff; 
   text-align: center;
  }

  .floatGif {
    width: 90px;
    height: 90px;
    position: fixed;
    bottom: 105px;
    right: -15px;
    z-index: 100;
  }
</style>